#include "net/TCPServer.h"
#include "net/TCPConnection.h"
#include "eventloop/Eventloop.h"
#include "net/Sockaddr.h"

#include <functional>
#include <string>

#include <stdio.h>
#include <unistd.h>

using namespace std::placeholders;

using TCPConnectionPtr = std::shared_ptr<TCPConnection>;

class TestServer
{
 public:
  TestServer(Eventloop* loop,
             const Sockaddr& listenAddr)
    : loop_(loop),
      server_(*loop, listenAddr, std::string{"TestServer"})
  {
    server_.set_connection_callback(
        std::bind(&TestServer::onConnection, this, _1));
    server_.set_message_callback(
        std::bind(&TestServer::onMessage, this, _1, _2, _3));
  }

  void start()
  {
	  server_.start();
  }

 private:
  void onConnection(const TCPConnectionPtr& conn)
  {
    if (conn->is_connected())
    {
      printf("onConnection(): new connection [%s] from %s\n",
             conn->name().c_str(),
             conn->peer().IP_port().c_str());
    }
    else
    {
      printf("onConnection(): connection [%s] is down\n",
             conn->name().c_str());
    }
  }

  void onMessage(const TCPConnectionPtr& conn,
                   const char* data,
                   ssize_t len)
  {
    printf("onMessage(): received %zd bytes from connection [%s], content: %s\n",
           len, conn->name().c_str(), data);
  }

  Eventloop* loop_;
  TCPServer server_;
};


int main()
{
  printf("main(): pid = %d\n", getpid());

  Sockaddr listenAddr(8888);
  Eventloop loop;

  TestServer server(&loop, listenAddr);
  server.start();

  loop.loop();
}